package com.yangy.flvdemo.ffmpeg;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 *
 * 调用指令ffmpeg，将rtsp转flv推流到nginx
 *
 * @author YangYuan
 * @date 2024/7/3
 */
public class RTSPToFLVStreamer {

    private static Logger log = LoggerFactory.getLogger(RTSPToFLVStreamer.class);

    private Process ffmpegProcess;
    private String ffmpegCommand;

    public RTSPToFLVStreamer(String ffmpegCommand) {
        this.ffmpegCommand = ffmpegCommand;
    }

    public void startStreaming(String code) {
        try {
            // Example ffmpeg command
//            String ffmpegCommand = "ffmpeg -rtsp_transport tcp -i rtsp://your_rtsp_url -c:v copy -c:a aac -f flv rtmp://your_nginx_server/your_application/your_stream_key";
            ProcessBuilder pb = new ProcessBuilder(ffmpegCommand.split(" "));
            pb.redirectErrorStream(true); // 将标准错误流合并到标准输出流
            ffmpegProcess = pb.start();




            // 读取FFmpeg的输出信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(ffmpegProcess.getInputStream()));
            String line;
            boolean isOpen = false;
            while ((line = reader.readLine()) != null) {
                log.info(line);
                if (line.startsWith("frame=") && !isOpen){
                    //开启监控
                    NginxConnectionMonitor nginxConnectionMonitor = new NginxConnectionMonitor(this);
                    nginxConnectionMonitor.startMonitoring(code);
                    isOpen = true;

                    //缓存执行的ffmpeg对象
                    VideoStreamerBucket.put(code, this);
                }
            }

            // 等待FFmpeg进程执行完毕
//            int exitCode = ffmpegProcess.waitFor();
//            System.out.println("FFmpeg process exited with code " + exitCode);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopStreaming() {
        if (ffmpegProcess != null) {
            ffmpegProcess.destroy();
        }
    }
}
